package com.itboye.sunsun.luntan;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.itboye.sunsunhome.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.TieZiCaoGaoBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.custome.FaceInputView;
import com.itboye.sunsun.custome.FaceInputView.Face;
import com.itboye.sunsun.custome.FaceInputView.OnFaceClickListener;
import com.itboye.sunsun.db.DBManager;
import com.itboye.sunsun.dialog.WaitDialog;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.uesrinfo.TieZiQuanXianManager;
import com.itboye.sunsun.utils.CameraPopupWindow;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.ImageCompress;
import com.itboye.sunsun.utils.PhotoSelectFragment;
import com.itboye.sunsun.utils.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.SmilyParser;
import com.itboye.sunsun.utils.Spanned2String;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.volley.ImageCompressAndUpload;
import com.itboye.sunsun.volley.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.String2Spanned;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.umeng.socialize.utils.Log;

public class FaBiaoTieZiActivity extends BaseActivity {

	ViewGroup imgContainer;
	TextView shenhyu;

	EditText content;
	ViewGroup faceInputContainer;

	WaitDialog wait;
	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;

	private int photoNum = 0;
	ArrayList<String> uploadedUrl = new ArrayList<>();
	Toast toast;
	EditText title;
	ImageView img;
	protected CameraPopupWindow mCameraPopupWindow;
	String inputContent = "";
	DBManager dbManager;
	protected String uid = "";

	@Override
	protected void onCreate(Bundle arg0) {

		super.onCreate(arg0);

		setContentView(R.layout.activity_luntan_fatie);
		dbManager = new DBManager(this);
		uid = SPUtils.get(FaBiaoTieZiActivity.this, null, SPContants.USER_ID,
				"") + "";
		ArrayList<TieZiCaoGaoBean> bean = dbManager.queryNote(SPUtils.get(this,

		null, SPContants.USER_ID, "") + "");
		// CopyOfTieZiCaoGaoBeanCopy bean2=new CopyOfTieZiCaoGaoBeanCopy();

		if (bean != null) {
			if (bean.size() > 0) {
				if (bean.get(0).getTitle() != null)
					Toast.makeText(this, bean.get(0).getTitle(), 0).show();
				title.setText(bean.get(0).getTitle());
				if (bean.get(0).getContent() != null)
					content.setText(String2Spanned.parsed(bean.get(0)
							.getContent()));
				// bean2.setContent(content.getText());
				// content.setText(bean.get(0).getContent());
				if (bean.get(0).getImg() != null
						&& !bean.get(0).getImg().equals("")) {
					String[] imgpath = bean.get(0).getImg().split(",");
					if (imgpath != null) {
						if (!imgpath.equals("[]")) {
							for (int i = 0; i < imgpath.length; i++) {
								imgPath.add(imgpath[i]);
								final View v = LayoutInflater
										.from(getApplicationContext())
										.inflate(
												R.layout.item_fabiao_tiezi_image_select,
												null);
								//
								v.setLayoutParams(new LayoutParams(
										(int) getResources().getDimension(
												R.dimen.tizie_imageview_width),
										LayoutParams.MATCH_PARENT));
								// Bitmap bit =
								// BitmapFactory.decodeFile(imgpath[i]);
								// ((ImageView)
								// v.findViewById(R.id.img)).setImageBitmap(bit);
								XImageLoader.load("file://" + imgpath[i],
										(ImageView) v.findViewById(R.id.img));
								v.setTag(imgpath[i]);
//								v.setTag(R.id.chat, i);
								imgContainer.addView(v,
										imgContainer.getChildCount() - 1);
								v.findViewById(R.id.del).setOnClickListener(
										new OnClickListener() {

											@Override
											public void onClick(View vvv) {
//												imgPath.remove(Integer.parseInt(v
//														.getTag(R.id.chat) + ""));
												imgContainer.removeView(v);
												shenhyu.setText("已选"
														+ (imgContainer
																.getChildCount() - 1)
														+ "张，还剩"
														+ (6 - imgContainer
																.getChildCount() + 1)
														+ "张可选");
											}
										});
								//
								shenhyu.setText("已选"
										+ (imgContainer.getChildCount() - 1)
										+ "张，还剩"
										+ (6 - imgContainer.getChildCount() + 1)
										+ "张可选");
							}
						}
					}
					//
				}
			}
		}
		toast = Toast.makeText(getApplicationContext(), "图片上传失败", 1);
		setStatusBarColor(R.color.top_blue);
		initView();
	}

	private void initView() {

		findViewById(R.id.back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!title.getText().toString().trim().equals("")
						|| !content.getText().toString().trim().equals("")
						|| imgContainer.getChildCount() > 1)
					showDialog();
				else {
					finish();
				}
			}
		});
		findViewById(R.id.send).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginController.onBBSPublishMessageClick(
						FaBiaoTieZiActivity.this, null);
			}
		});
		findViewById(R.id.emoj).setOnClickListener(new OnClickListener() {

			private FaceInputView faceInputView;

			@Override
			public void onClick(View v) {
				v.setSelected(!v.isSelected());
				if (faceInputView == null) {
					faceInputView = new FaceInputView(getApplicationContext());
					faceInputContainer.addView(faceInputView);
					faceInputView.setOnClickListener(new FaceInputListenr());
				}
				if (v.isSelected()) {
					InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					inputMethodManager.hideSoftInputFromWindow(
							content.getWindowToken(), 0);
					faceInputView.setVisibility(View.VISIBLE);

				} else {
					faceInputView.setVisibility(View.GONE);

				}
			}
		});
		findViewById(R.id.img).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mCameraPopupWindow = new CameraPopupWindow(
						FaBiaoTieZiActivity.this, onclicklister);
				mCameraPopupWindow.showAtLocation(
						FaBiaoTieZiActivity.this.findViewById(R.id.add),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});
		findViewById(R.id.add).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				mCameraPopupWindow = new CameraPopupWindow(
						FaBiaoTieZiActivity.this, onclicklister);
				mCameraPopupWindow.showAtLocation(
						FaBiaoTieZiActivity.this.findViewById(R.id.add),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
				// new PhotoSelectFragment(new PhotoSelect(), 6 - imgContainer
				// .getChildCount() + 1).show(getSupportFragmentManager(),
				// null);
			}
		});
	}

	// private String path = Environment.getExternalStorageDirectory() +
	// "/aImage/";
	private String fileName;

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				if (imgContainer.getChildCount() > 6) {
					Toast.makeText(FaBiaoTieZiActivity.this, "最多上传6张照片", 0)
							.show();
					return;
				}
				/**
				 * 打开照相机
				 */
				picture_name = android.text.format.DateFormat.format(
						"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(fileName)));
				startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);

				// String state = Environment.getExternalStorageState();
				// if (state.equals(Environment.MEDIA_MOUNTED)) {
				// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// startActivityForResult(intent,
				// CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				// } else {
				// Toast.makeText(FaBiaoTieZiActivity.this, "请确认已经插入SD卡", 0)
				// .show();
				// }
				break;
			case R.id.pick_image:
				new PhotoSelectFragment(new PhotoSelect(),
						6 - imgContainer.getChildCount() + 1).show(
						getSupportFragmentManager(), null);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 监听Back键按下事件,方法2: 注意: 返回值表示:是否能完全处理该事件 在此处返回false,所以会继续传播该事件.
	 * 在具体项目中此处的返回值视情况而定.
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			if (!title.getText().toString().trim().equals("")
					|| !content.getText().toString().trim().equals("")
					|| imgContainer.getChildCount() > 1)
				showDialog();
			else {
				finish();
			}
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	private void showDialog() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				FaBiaoTieZiActivity.this).create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.dialog_save);
		TextView tv_title = (TextView) window.findViewById(R.id.title);
		tv_title.setText("提示");
		TextView tv_message = (TextView) window.findViewById(R.id.message);
		tv_message.setText("是否保存编辑内容");
		Button btn_save = (Button) window.findViewById(R.id.save);
		Button btn_noSave = (Button) window.findViewById(R.id.noSave);
		Button canButton = (Button) window.findViewById(R.id.cancel);
		btn_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String save_title = title.getText().toString().trim();
				String save_content = content.getText().toString().trim();
				StringBuilder builder = new StringBuilder();
				for (int i = 0; i < imgPath.size(); i++) {
					builder.append(imgPath.get(i) + ",");
				}

				String s = "";
				if (builder.length() > 0) {
					s = builder.toString().substring(0, builder.length() - 1);
				}
				dbManager.delete(uid);
				long result = dbManager.addNote(uid, save_title,
						Spanned2String.parse(content.getText()), s);
				if (result <= 0) {
					Toast.makeText(FaBiaoTieZiActivity.this, "保存草稿失败", 0)
							.show();
				} else {
					Toast.makeText(FaBiaoTieZiActivity.this, "保存草稿成功", 0)
							.show();
				}
				finish();
			}
		});
		btn_noSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dbManager.delete(uid);
				finish();
			}
		});
		canButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.dismiss();
			}
		});

	}

	public void onPublicBBsClick() {
		if (!TieZiQuanXianManager.canPublishMessage(getIntent().getStringExtra(
				"fid"))) {
			Toast.makeText(getApplicationContext(), "无权发帖", 1).show();
			return;
		}
		if (title.getText().toString().trim().length() == 0) {
			Toast.makeText(getApplicationContext(), "请输入标题", 1).show();
			return;
		}
		if (content.getText().toString().trim().length() == 0) {
			Toast.makeText(getApplicationContext(), "请输入内容", 1).show();
			return;
		}
		uploadedUrl.clear();

		if (imgContainer.getChildCount() == 1) {
			sendToServer();
		} else {
			if (wait == null) {
				wait = new WaitDialog();
			}
			wait.show(getSupportFragmentManager(), null);
			for (int i = 0; i < imgContainer.getChildCount() - 1; i++) {

				ImageCompressAndUpload.getInstance().execute(
						(String) imgContainer.getChildAt(i).getTag(),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);
								DebugLog.v("bytag", resultData);
								if (uploadedUrl.size() == imgContainer
										.getChildCount() - 1) {
									if (wait != null) {
										wait.dismiss();
									}

									sendToServer();
								}
							}

							@Override
							public void OnError(String resultData) {
								if (wait != null) {
									wait.dismiss();
								}

								toast.show();
							}
						});

			}

		}
	}

	private void sendToServer() {
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<>();
		builder.apiVer("100")
				.typeKey("BY_ForumThread_add")
				.param("fid", getIntent().getStringExtra("fid"))
				.param("typeid", "0")
				.param("author",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.NICK, ""))
				.param("author_id",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.param("subject", title.getText().toString())
				.param("message", Spanned2String.parse(content.getText()));

		if (uploadedUrl.size() > 0) {
			StringBuilder sb = new StringBuilder();
			sb.append(uploadedUrl.get(0));
			for (int i = 1; i < uploadedUrl.size(); i++) {
				sb.append(",").append(uploadedUrl.get(i));
			}

			builder.param("attachments", sb.toString());

		}

		builder.requestListener(new XRequestListener<String>() {

			@Override
			public void onResponse(String arg0) {
				// TODO Auto-generated method stub
				dbManager.delete(SPUtils.get(FaBiaoTieZiActivity.this, null,
						SPContants.USER_ID, "") + "");
				Toast.makeText(FaBiaoTieZiActivity.this, arg0, 0).show();
				Intent intent = new Intent("refresh");
				sendBroadcast(intent);
				finish();
			}
		}).errorListener(new XErrorListener() {

			@Override
			public void onErrorResponse(Exception exception, int code,
					String msg) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), msg, 1).show();

				Log.v("errorcode", "haha" + code);
				Log.v("errormsg", "haha" + msg);
			}
		});
		HttpRequest.getDefaultRequestQueue().add(builder.build());

	}

	private class FaceInputListenr implements OnFaceClickListener {

		@Override
		public void selectedFace(Face face) {
			int id = face.faceId;
			if (id == R.drawable.ic_face_delete_normal)// 删除按钮
			{
				int index = content.getSelectionStart();
				if (index == 0)
					return;
				Editable editable = content.getText();
				editable.delete(index - 1, index);// 删除最后一个字符或表情
			} else {
				content.append(Html.fromHtml("<img src='" + id + "'/>",
						imageGetter, null));// 添加表情
			}
		}

	}

	// 输入表情需要
	ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			Drawable d = getResources().getDrawable(id);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			return d;
		}
	};
	private String picture_name;
	public ArrayList<String> imgPath = new ArrayList<String>();
	int index = -1, index2 = -1;

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				index++;
				imgPath.add(string);
				final View v = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.item_fabiao_tiezi_image_select, null);

				v.setLayoutParams(new LayoutParams((int) getResources()
						.getDimension(R.dimen.tizie_imageview_width),
						LayoutParams.MATCH_PARENT));
				Bitmap bit = BitmapFactory.decodeFile(string);
				int degree = ImageCompress.readPictureDegree(string);
				if (degree <= 0) {

				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// // 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);

				}
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				FileOutputStream b = null;
				try {
					b = new FileOutputStream(string);
					bit.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				// saveImage(bit, new File(string));
				// ((ImageView) v.findViewById(R.id.img)).setImageBitmap(bit);
				XImageLoader.load("file://" + string,
						(ImageView) v.findViewById(R.id.img));
				v.setTag(string);
				v.setTag(R.id.tabs, index);
				imgContainer.addView(v, imgContainer.getChildCount() - 1);
				mCameraPopupWindow.dismiss();
				v.findViewById(R.id.del).setOnClickListener(
						new OnClickListener() {

							@Override
							public void onClick(View vvv) {
								System.out.println(vvv.getTag(R.id.tabs)
										+ "索引下表、");
								imgPath.remove(v.getTag(R.id.tabs));
								imgContainer.removeView(v);
								shenhyu.setText("已选"
										+ (imgContainer.getChildCount() - 1)
										+ "张，还剩"
										+ (6 - imgContainer.getChildCount() + 1)
										+ "张可选");
							}
						});

				shenhyu.setText("已选" + (imgContainer.getChildCount() - 1)
						+ "张，还剩" + (6 - imgContainer.getChildCount() + 1)
						+ "张可选");
			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
			if (resultCode == RESULT_OK) {
				Bitmap bit = BitmapFactory.decodeFile(fileName);
				int degree = ImageCompress.readPictureDegree(fileName);
				if (degree <= 0) {
					// show_Image.setImageBitmap(bm);
				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);
				}
				saveImage(bit, new File(fileName));
			} else {
				Toast.makeText(FaBiaoTieZiActivity.this, "拍照取消", 0).show();
			}
			mCameraPopupWindow.dismiss();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void saveImage(Bitmap data, File fileName) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.i("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}
		FileOutputStream b = null;
		try {
			b = new FileOutputStream(fileName);
			data.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			final View v = LayoutInflater.from(getApplicationContext())
					.inflate(R.layout.item_fabiao_tiezi_image_select, null);

			v.setLayoutParams(new LayoutParams((int) getResources()
					.getDimension(R.dimen.tizie_imageview_width),
					LayoutParams.MATCH_PARENT));
			v.setTag(this.fileName);
			v.findViewById(R.id.del).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View vvv) {
					imgContainer.removeView(v);
					shenhyu.setText("已选" + (imgContainer.getChildCount() - 1)
							+ "张，还剩" + (6 - imgContainer.getChildCount() + 1)
							+ "张可选");
				}
			});

			shenhyu.setText("已选" + (imgContainer.getChildCount()) + "张，还剩"
					+ (6 - imgContainer.getChildCount()) + "张可选");
			((ImageView) v.findViewById(R.id.img)).setImageBitmap(data);
			imgContainer.addView(v, imgContainer.getChildCount() - 1);
		} catch (Exception e) {
			Log.e("error", e.getMessage());
		}
	}

}
